package com.dr.cmdb.core.service.impl;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.dr.cmdb.common.model.errorcode.BaseCode;
import com.dr.cmdb.common.utils.excel.ExcelUtil;
import com.dr.cmdb.core.config.CustomizeConfig;
import com.dr.cmdb.core.dto.TableModelsDto;
import com.dr.cmdb.core.annotation.RedisLock;
import com.dr.cmdb.core.errorcode.BizCode;
import com.dr.cmdb.core.exception.BizException;
import com.dr.cmdb.core.mapper.TablesModelMapper;
import com.dr.cmdb.core.mongodao.MongoTempleDao;
import com.dr.cmdb.core.service.CiItemService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ProjectName: cmdb
 * @Package: com.dr.cmdb.application.service.impl
 * @Description: java类作用描述
 * @Author: duanrui
 * @CreateDate: 2021/3/18 9:45
 * @Version: 1.0
 * <p>
 * Copyright: Copyright (c) 2021
 */
@Service
public class CiItemServiceImpl implements CiItemService {

    @Autowired
    private MongoTempleDao mongoTempleDao;

    @Autowired
    private CustomizeConfig customizeConfig;

    @Autowired
    private TablesModelMapper tablesModelMapper;


    /**
     * 添加ci项
     *
     * @param params
     */
    @RedisLock(lockKey = "add_mongodb")
    @Override
    public void addCiItem(Map<String, Object> params) {
        params.put("createTime", new Date());
        params.put("modifyTime", new Date());
        mongoTempleDao.save(params, customizeConfig.getCiCollectName());
    }


    /**
     * 修改ci项
     *
     * @param params
     */
    @Override
    public void editCiItem(Map<String, Object> params) {
        params.put("updateTime", new Date());
        mongoTempleDao.edit(params, customizeConfig.getCiCollectName());
    }


    /**
     * 删除ci项
     *
     * @param code
     */
    @Override
    public void deleteCiItem(String code) {
        mongoTempleDao.delete(code, customizeConfig.getCiCollectName());
    }

    /**
     * 添加ci项集合
     *
     * @param list
     */
    @RedisLock(lockKey = "mongo_lock")
    @Override
    public void addCiItems(List<Map<String, Object>> list) {
        mongoTempleDao.saveList(list, customizeConfig.getCiCollectName());
    }

    /**
     * 获取ci列表
     *
     * @return
     */
    @Override
    public List<Object> getListByParams(Map<String, Object> map) {
        return mongoTempleDao.getListByParams(map, customizeConfig.getCiCollectName());
    }


    /**
     * 导出查询数据
     *
     * @param searchMap
     * @param fileName
     * @param sheetName
     * @param response
     */
    @Override
    public void exportCiItems(Map<String, Object> searchMap, String fileName, String sheetName, HttpServletResponse response) {
        if (CollectionUtils.isEmpty(searchMap) || !searchMap.containsKey(customizeConfig.getCiTableName())) {
            throw new BizException(BaseCode.PARAM_ERROR);
        }
        String tableName = (String) searchMap.get(customizeConfig.getCiTableName());
        //获取导出字段
        List<TableModelsDto> tableCols = tablesModelMapper.selectByTableName(tableName);
        if (CollectionUtils.isEmpty(tableCols)) {
            throw new BizException(BizCode.EXPORT_FIELD_NOT_EXIST);
        }
        Map<String, String> colMap = tableCols.stream().filter(TableModelsDto::getExportFlag).collect(Collectors.toMap(TableModelsDto::getModelName, TableModelsDto::getModelDes));
        if (CollectionUtils.isEmpty(colMap)) {
            throw new BizException(BizCode.EXPORT_FIELD_NOT_EXIST);
        }
        //构造对象等同于@Excel
        List<ExcelExportEntity> entitys = Lists.newArrayList();
        colMap.forEach(
                (k, v) -> {
                    ExcelExportEntity entity = new ExcelExportEntity(v, k);
                    entitys.add(entity);
                }
        );
        //获取需要导出的数据
        List<Object> list = mongoTempleDao.getListByParams(searchMap, customizeConfig.getCiCollectName());
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException(BaseCode.EXPORT_OBJECT_EMPTY);
        }
        ArrayList<Map<String, Object>> listMap = Lists.newArrayList();
        list.forEach(
                e -> {
                    listMap.add((Map<String, Object>) e);
                }
        );
        ExcelUtil.exportExcel(entitys, listMap, fileName, sheetName, response);
    }

    /**
     * 导入配置项数据
     *
     * @param list
     * @param tableName
     */
    @Override
    public void importCiItems(List<Map<String, Object>> list, String tableName) {
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException(BaseCode.PARAM_ERROR);
        }
        //获取导入字段
        List<TableModelsDto> tableCols = tablesModelMapper.selectByTableName(tableName);
        if (CollectionUtils.isEmpty(tableCols)) {
            throw new BizException(BizCode.EXPORT_FIELD_NOT_EXIST);
        }
        //获取可以导入的字段，存储为 显示名-》字段名的格式，然后转换
        Map<String, String> colMap = tableCols.stream().filter(TableModelsDto::getImportFlag).collect(Collectors.toMap(TableModelsDto::getModelDes, TableModelsDto::getModelName));
        if (CollectionUtils.isEmpty(colMap)) {
            throw new BizException(BizCode.EXPORT_FIELD_NOT_EXIST);
        }
        List<Map<String, Object>> collectMap = list.stream().map(e -> {
            Map<String, Object> ciMap = new HashMap<>(e.size());
            e.forEach(
                    (k, v) -> {
                        ciMap.put(colMap.get(k), v);
                    }
            );
            ciMap.put(customizeConfig.getCiTableName(), tableName);
            ciMap.put("createTime", new Date());
            return ciMap;
        }).collect(Collectors.toList());
        addCiItems(collectMap);

    }
}
